﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Common;
using WarehouseManagement.BO;
using WarehouseManagement.Header;

namespace WarehouseManagement.UI
{
    public partial class DonDatHang : Form
    {
        public const string
            DDH_COL_NGAY_DH = "NgayDatHang",
            DDH_COL_PMHID = "PMHID";

        public const int
            IDX_VTID = 0,
            IDX_NGANG = 3,
            IDX_CAO = 4,
            IDX_SAU = 5,
            IDX_SOLUONG = 6,
            IDX_GHI_CHU = 8,
            IDX_NGAY_DH = 9,
            IDX_NCC_ID = 15,
            
            NCC_ALL_VALUE = 9999

            ;

        SqlConnection conn;
        CommonDO cmDO;
        bool isFormLoad = false;
        bool isCbbNCCLoaded = false;

        // store data
        DataTable tbNhaCungCap, tbVatTu, tbListDonDatHang, tbDataGrid;

        // variables
        string currentPMHID, oldVTID; 

        // current working user
        string sNhanVienID, sTenNhanVien;

        public DonDatHang(SqlConnection conn1, string sNVID, string sTenNV)
        {
            InitializeComponent();
            cmDO = new CommonDO();
            conn = conn1;
            sNhanVienID = sNVID;
            sTenNhanVien = sTenNV;

            LoadNhaCungCap();
            cbbNCC.SelectedValue = NCC_ALL_VALUE;
            isFormLoad = true;
            LoadVatTu();
            currentPMHID = "";
            oldVTID = "";
        }

        private void LoadNhaCungCap()
        {
            isCbbNCCLoaded = false;
            string cmd = "select NCCID, TenCongTy from NhaCungCap";

            string ret = cmDO.getTable(conn, ref tbNhaCungCap, cmd);

            if (ret != CommonHeader.NO_ERROR)
            {
                ShowMsg("Không thể lấy thông tin nhà cung cấp", 2);
                return;
            }

            tbNhaCungCap.Rows.Add();
            tbNhaCungCap.Rows[tbNhaCungCap.Rows.Count - 1][0] = NCC_ALL_VALUE;
            tbNhaCungCap.Rows[tbNhaCungCap.Rows.Count - 1][1] = "All";
            tbNhaCungCap.AcceptChanges();

            cbbNCC.DataSource = tbNhaCungCap;
            cbbNCC.DisplayMember = "TenCongTy";
            cbbNCC.ValueMember = "NCCID";
            isCbbNCCLoaded = true;
        }

        private void LoadVatTu()
        { 
            if ( isFormLoad )
            {
                try
                {
                    string cmd = "SELECT VTID ,TenVatTu,Ngang,Cao,Sau FROM VatTu where NCC = N'" 
                                + cbbNCC.SelectedValue.ToString() + "'";
                    string ret = cmDO.getTable(conn, ref tbVatTu, cmd);

                    if (ret != CommonHeader.NO_ERROR)
                    {
                        ShowMsg("Không thể lấy vật tư của nhà cung cấp : " + cbbNCC.Text, 2);
                        return;
                    }
                    cbbVatTu.DataSource = null;
                    cbbVatTu.DataSource = tbVatTu;

                    cbbVatTu.DisplayMember = "TenVatTu";
                    cbbVatTu.ValueMember = "VTID";

                    if (tbVatTu.Rows.Count > 0)
                    {
                        cbbVatTu.Enabled = true;
                    }
                    else
                    {
                        cbbVatTu.Enabled = false;
                    }
                }
                catch
                {
                    // Do nothing
                }

            }
        }

        public void ShowMsg(string Msg, int typeMsg)
        {
            switch (typeMsg)
            {
                case 0: // Info message
                    MessageBox.Show(Msg, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    break;
                case 1: // Warning message
                    MessageBox.Show(Msg, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    break;
                case 2: // Error message
                    MessageBox.Show(Msg, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    break;
            }
        }

        private void cbbNCC_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                LoadVatTu();
                loadDataGrid(currentPMHID);                
            }
            catch (Exception ex)
            {
                ShowMsg("cbbNCC_SelectedIndexChanged", 2);
            }
        }

        private void btnLoadTree_Click(object sender, EventArgs e)
        {
            foreach (TreeNode node in treeView1.Nodes)
            {
                treeView1.Nodes.Remove(node);
            }

            loadTreeVIew(dpkFrom.Value.ToShortDateString(), dpkTo.Value.ToShortDateString());
            treeView1.Focus();
        }

        private void loadTreeVIew(string dateFrom, string dateTo)
        {
            DataTable tbVersion = new DataTable();
            string ret = "";

            treeView1.Nodes.Clear();

            string dtFrom = string.Format("{0:yyyy-MM-dd}", dpkFrom.Value);
            string dtTo = string.Format("{0:yyyy-MM-dd}", dpkTo.Value);

            // Lay ngay co don dat hang
            string cmd = "select distinct " + DDH_COL_NGAY_DH + " from DonDatHang "
                        + "where " + DDH_COL_NGAY_DH + " between '" + dtFrom + "' and '" + dtTo + "'";
            ret = cmDO.getTable(conn, ref tbListDonDatHang, cmd);

            if (ret != CommonHeader.NO_ERROR)
            {
                ShowMsg("Không thể lấy danh sách đơn đặt hàng : " + cbbNCC.Text, 2);
                return;
            }
            string dtValue;
            //Level : Ngay co don dat hang
            TreeNode tnLevel1;

            if (tbListDonDatHang.Rows.Count < 1)
            {
                if ((dpkFrom.Value.Date <= DateTime.Now.Date) && (dpkTo.Value.Date >= DateTime.Now.Date))
                {
                    dtValue = string.Format("{0:d}", DateTime.Parse(DateTime.Now.ToString()));
                    tnLevel1 = new TreeNode(dtValue);
                    tnLevel1.Name = dtValue;
                    treeView1.Nodes.Add(tnLevel1);
                }
                return;
            }
            for (int i = 0; i < tbListDonDatHang.Rows.Count; i++)
            {
                // lay du lieu Hang muc sang pham
                DataTable tbDDH = new DataTable();
                // Lay ngay co don dat hang
                cmd = "select distinct PMHID from DonDatHang "
                            + "where " + DDH_COL_NGAY_DH + " = N'"+ tbListDonDatHang.Rows[ i ][ DDH_COL_NGAY_DH ].ToString() +"'";
                ret = cmDO.getTable(conn, ref tbDDH, cmd);

                if (ret != CommonHeader.NO_ERROR)
                {
                    ShowMsg("Không thể lấy danh sách đơn đặt hàng : " + cbbNCC.Text, 2);
                    return;
                }
                dtValue = string.Format("{0:yyyy-MM-dd}", tbListDonDatHang.Rows[i][DDH_COL_NGAY_DH].ToString());
                dtValue = string.Format("{0:d}", DateTime.Parse(dtValue));

                if (tbDDH.Rows.Count > 0)
                {
                    TreeNode[] tnLevel2 = new TreeNode[tbDDH.Rows.Count];
                    for (int i2 = 0; i2 < tbDDH.Rows.Count; i2++)
                    {
                        tnLevel2[i2] = new TreeNode(tbDDH.Rows[i2]["PMHID"].ToString());
                        tnLevel2[i2].Name = tbDDH.Rows[i2]["PMHID"].ToString();
                    }
                    tnLevel1 = new TreeNode(dtValue, tnLevel2);
                }
                else
                {
                    tnLevel1 = new TreeNode(dtValue);
                }
                tnLevel1.Name = tbListDonDatHang.Rows[i][DDH_COL_NGAY_DH].ToString();
                treeView1.Nodes.Add(tnLevel1);
            }
        }

        private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Node.Level == 0)
            {
                if (e.Button == MouseButtons.Right)
                {
                    ctxAddVersion.Enabled = true;
                    ctxUpdateVersion.Enabled = false;
                    ctxDeleteVersion.Enabled = false;
                    contextTreeView.Show(Cursor.Position);
                }
                dtgDonDatHang.DataSource = null;
                currentPMHID = "";
                btnAdd.Enabled = false;
                btnUpdate.Enabled = false;
                btnAdd.Enabled = false;
                btnLoad.Enabled = false;
            }
            else if ( e.Node.Level == 1 )
            {
                currentPMHID = e.Node.Name;
                if (e.Button == MouseButtons.Right)
                {
                    ctxAddVersion.Enabled = false;
                    ctxUpdateVersion.Enabled = true;
                    ctxDeleteVersion.Enabled = true;
                    contextTreeView.Show(Cursor.Position);
                }
                if (cbbNCC.SelectedValue.ToString() == NCC_ALL_VALUE.ToString())
                {
                    loadDataGrid(e.Node.Name);
                }
                else
                {
                    cbbNCC.SelectedValue = NCC_ALL_VALUE;
                }
                btnLoad.Enabled = true;
                btnDelete.Enabled = true;
                cbbNCC.Focus();

            }
        }

        private void loadDataGrid( string sPMHID )
        {
            string cmd;
            if (isFormLoad)
            {
                try
                {
                    if (cbbNCC.SelectedValue.ToString() == NCC_ALL_VALUE.ToString())
                    {
                        // Load data don dat hang dua vao DDHID
                        cmd = "select * from ViewDonDatHang where PMHID = N'" + sPMHID + "'";
                        btnAdd.Enabled = false;
                    }
                    else
                    {
                        cmd = "select * from ViewDonDatHang where PMHID = N'" + sPMHID
                                + "' and NCCID = N'" + cbbNCC.SelectedValue.ToString() + "'";
                        btnAdd.Enabled = true;
                    }
                    string ret = cmDO.getTable(conn, ref tbDataGrid, cmd);

                    if (ret != CommonHeader.NO_ERROR)
                    {
                        ShowMsg("Không thể load data đơn đặt hàng ", 2);
                        return;
                    }

                    dtgDonDatHang.DataSource = tbDataGrid;
                    dtgDonDatHang.CurrentCell = null;
                }
                catch (System.Exception ex)
                {
                    ShowMsg("Get data failed", 2);
                }
            }
        }    

        private void dtgDonDatHang_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            // If select to column header
            if ((e.RowIndex < 0) || (cbbNCC.SelectedValue.ToString() == NCC_ALL_VALUE.ToString()))
            {
                if (e.RowIndex < 0)
                {
                    dtgDonDatHang.CurrentCell = null;
                    btnDelete.Enabled = false;
                }
                else
                {
                    btnDelete.Enabled = true;
                    oldVTID = tbDataGrid.Rows[e.RowIndex]["VTID"].ToString();
                }
                // Binding data to controls
                txtNgang.Text = "";
                txtCao.Text = "";
                txtSau.Text = "";
                txtSoLuong.Text = "";
                txtGhiChu.Text = "";

                // Disable controls
                btnUpdate.Enabled = false;
                return;
            }
            oldVTID = tbDataGrid.Rows[e.RowIndex]["VTID"].ToString();
            selectID(oldVTID);
            btnAdd.Enabled = true;
            btnUpdate.Enabled = true;
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            // check input value
            if (!CheckNumber())
            {
                return;
            }

            if (InsertData(cbbVatTu.SelectedValue.ToString(),
                        txtNgang.Text,
                        txtCao.Text,
                        txtSau.Text,
                        txtSoLuong.Text,
                        txtGhiChu.Text))
            {
                loadDataGrid(currentPMHID);
                selectID(cbbVatTu.SelectedValue.ToString());
                oldVTID = cbbVatTu.SelectedValue.ToString();
            }
        }

        private bool InsertData( string sVTID, string sNgang, string sCao, string sSau, string sSL, string sGhiChu )
        {
            DataTable temp = new DataTable();
            string cmd = "select PMHID from DonDatHang where PMHID = N'"
                            + currentPMHID + "' and VTID = N'" + sVTID + "'";

            string ret = cmDO.getTable(conn, ref temp, cmd);

            if (ret != CommonHeader.NO_ERROR)
            {
                ShowMsg("kiểm tra dữ liệu trùng thất bại", 2);
                return false;
            }

            if (temp.Rows.Count > 0)
            {
                ShowMsg("Đã có data này trong database, không thể thêm mới", 1);
                temp.Dispose();
                return false;
            }


            string dtNgayDH = "";
            if (dtgDonDatHang.RowCount == 0)
            {
                dtNgayDH = string.Format("{0:yyyy-MM-dd}", dtpNgayDatHang.Value);
            }
            else
            {
                dtNgayDH = tbDataGrid.Rows[0]["NgayDatHang"].ToString();
                dtNgayDH = string.Format("{0:d}", DateTime.Parse(dtNgayDH));
            }

            // Load data don dat hang dua vao DDHID
            cmd = "DonDatHang_add N'" + currentPMHID + "'"
                        + ",N'" + sVTID + "'"
                        + ",N'" + sNgang + "'"
                        + ",N'" + sCao + "'"
                        + ",N'" + sSau + "'"
                        + ",N'" + sSL + "'"
                        + ",N'" + sGhiChu + "'"
                        + ",N'" + dtNgayDH + "'";


            ret = cmDO.InsertUpdateRecord(conn, cmd);

            if (ret != CommonHeader.NO_ERROR)
            {
                ShowMsg("Thêm dữ liệu không thành công", 2);
                return false;
            }
            temp.Dispose();
            return true;
        }

        private bool CheckNumber()
        {
            int iC = 0;

            if (currentPMHID == "")
            {
                ShowMsg("Bạn chưa chọn mã đơn đặt hàng", 2);
                return false;
            }

            if (cbbVatTu.SelectedIndex < 0)
            {
                ShowMsg("Vật tư không hợp lệ", 2);
                cbbVatTu.Focus();
                return false;
            }

            try
            {
                double.Parse(txtNgang.Text);
                iC = 1;
                double.Parse(txtCao.Text);
                iC = 2;
                double.Parse(txtSau.Text);
                iC = 3;
                double.Parse(txtSoLuong.Text);
                return true;
            }
            catch (System.Exception ex)
            {
                ShowMsg("Giá trị nhập vào không hợp lệ",2);
                switch (iC)
                {
                    case 0:
                        {
                            txtNgang.Focus();
                            break;
                        }
                    case 1:
                        {
                            txtCao.Focus();
                            break;
                        }
                    case 2:
                        {
                            txtSau.Focus();
                            break;
                        }
                    case 3:
                        {
                            txtSoLuong.Focus();
                            break;
                        }
                }
                return false;
            }
        }

        private void ctxAddVersion_Click(object sender, EventArgs e)
        {            
            TreeNode newNode = new TreeNode(DateTime.Now.ToShortDateString());
            newNode.Name = DateTime.Now.ToShortDateString();
            treeView1.SelectedNode.Nodes.Add(newNode);
            treeView1.SelectedNode = newNode;
            currentPMHID = newNode.Name;
        }

        private void ctxUpdateVersion_Click(object sender, EventArgs e)
        {
            txtEditNode.Bounds = treeView1.SelectedNode.Bounds;
            txtEditNode.Width = 100;
            txtEditNode.Visible = true;
            txtEditNode.Text = treeView1.SelectedNode.Text;
            txtEditNode.Focus();
            txtEditNode.Select(0, 100);
        }

        private void txtEditNode_Leave(object sender, EventArgs e)
        {
            txtEditNode.Visible = false;
            string oldPMHID = treeView1.SelectedNode.Name;
            if ((txtEditNode.Text != "") ||(txtEditNode.Text.ToUpper() == oldPMHID.ToUpper()))
            {
               // Load data don dat hang dua vao DDHID
                string cmd = "Update DonDatHang Set PMHID = N'" 
                                + txtEditNode.Text + "' where PMHID = N'"+ oldPMHID +"'";                          

                string ret = cmDO.InsertUpdateRecord(conn, cmd);

                if (ret != CommonHeader.NO_ERROR)
                {
                    ShowMsg("Update đơn đặt hàng không thành công", 2);
                    return;
                }

                treeView1.SelectedNode.Name = txtEditNode.Text;
                treeView1.SelectedNode.Text = txtEditNode.Text;
                currentPMHID = txtEditNode.Text;
                loadDataGrid(currentPMHID);
            }
        }

        private void selectID(string sID)
        {
            int iRowIdx = -1;
            for (int i = 0; i < tbDataGrid.Rows.Count; i++)
            {
                if (sID == tbDataGrid.Rows[i]["VTID"].ToString())
                {
                    //dtgDonDatHang.Rows[i].Selected = true;
                    dtgDonDatHang.CurrentCell = dtgDonDatHang.Rows[i].Cells[0];
                    iRowIdx = i;
                    break;
                }
            }

            try
            {             
                // Binding data to controls
                //cbbNCC.SelectedValue = tbDataGrid.Rows[iRowIdx][IDX_NCC_ID].ToString();
                if (cbbNCC.SelectedValue.ToString() != NCC_ALL_VALUE.ToString())
                {
                    cbbVatTu.SelectedValue = tbDataGrid.Rows[iRowIdx]["VTID"].ToString();
                    txtNgang.Text = tbDataGrid.Rows[iRowIdx][IDX_NGANG].ToString();
                    txtCao.Text = tbDataGrid.Rows[iRowIdx][IDX_CAO].ToString();
                    txtSau.Text = tbDataGrid.Rows[iRowIdx][IDX_SAU].ToString();
                    txtSoLuong.Text = tbDataGrid.Rows[iRowIdx][IDX_SOLUONG].ToString();
                    txtGhiChu.Text = tbDataGrid.Rows[iRowIdx][IDX_GHI_CHU].ToString();
                    if (txtGhiChu.Text == " ")
                    {
                        txtGhiChu.Text = "";
                    }

                    // Enable controls
                    btnAdd.Enabled = true;
                    btnUpdate.Enabled = true;
                }
                btnDelete.Enabled = true;
            }
            catch (System.Exception ex)
            {
                dtgDonDatHang.CurrentCell = null;
                btnAdd.Enabled = false;
                btnDelete.Enabled = false;
                btnUpdate.Enabled = false;
            } 
        }

        private void ctxDeleteVersion_Click(object sender, EventArgs e)
        {
            string oldPMHID = treeView1.SelectedNode.Name;
            if (MessageBox.Show("Bạn có muốn xóa phiếu đặt hàng [" + oldPMHID + "] không ?",
                                "Confirm",MessageBoxButtons.YesNo,
                                MessageBoxIcon.Warning) == DialogResult.Yes)
            {
               // Load data don dat hang dua vao DDHID
                string cmd = "Delete DonDatHang where PMHID = N'"+ oldPMHID +"'";                          

                string ret = cmDO.InsertUpdateRecord(conn, cmd);

                if (ret != CommonHeader.NO_ERROR)
                {
                    ShowMsg("Xóa đơn đặt hàng không thành công", 2);
                    return;
                }

                treeView1.Nodes.Remove(treeView1.SelectedNode);
                currentPMHID = "";
                loadDataGrid(currentPMHID);
            }   
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            // check input value
            if (!CheckNumber())
            {
                return;
            }

            string dtNgayDH = string.Format("{0:yyyy-MM-dd}", dtpNgayDatHang.Value);
            // Load data don dat hang dua vao DDHID
            string cmd = "DonDatHang_update N'" + currentPMHID + "'"
                        + ",N'" + cbbVatTu.SelectedValue.ToString() + "'"
                        + ",N'" + txtNgang.Text + "'"
                        + ",N'" + txtCao.Text + "'"
                        + ",N'" + txtSau.Text + "'"
                        + ",N'" + txtSoLuong.Text + "'"
                        + ",N'" + txtGhiChu.Text + "'"
                        + ",N'" + dtNgayDH + "'"
                        + ",N'" + oldVTID + "'";


            string ret = cmDO.InsertUpdateRecord(conn, cmd);

            if (ret != CommonHeader.NO_ERROR)
            {
                ShowMsg("Update dữ liệu không thành công", 2);
                return;
            }

            loadDataGrid(currentPMHID);
            selectID(cbbVatTu.SelectedValue.ToString());
            oldVTID = cbbVatTu.SelectedValue.ToString();
        }

        private void dtgDonDatHang_KeyDown(object sender, KeyEventArgs e)
        {
            int currRowIdx = -1;
            if (e.KeyCode == Keys.Down)
            {
                if (dtgDonDatHang.SelectedRows.Count > 0)
                {
                    currRowIdx = dtgDonDatHang.CurrentCell.RowIndex;
                    if (currRowIdx < dtgDonDatHang.RowCount - 1)
                    {
                        currRowIdx += 1;
                    }
                }
                else if (dtgDonDatHang.RowCount > 0)
                {
                    currRowIdx = 0;
                }
                else return;

                oldVTID = dtgDonDatHang.Rows[currRowIdx].Cells[0].Value.ToString();
                selectID(oldVTID);
            }
            else if (e.KeyCode == Keys.Up)
            {
                if (dtgDonDatHang.SelectedRows.Count > 0)
                {
                    currRowIdx = dtgDonDatHang.CurrentCell.RowIndex;
                    if (currRowIdx > 0)
                    {
                        currRowIdx -= 1;
                    }
                }
                else if (dtgDonDatHang.RowCount > 0)
                {
                    currRowIdx = 0;
                }
                else return;
                oldVTID = dtgDonDatHang.Rows[currRowIdx].Cells[0].Value.ToString();
                selectID(oldVTID);
            }
            else if ((e.KeyCode == Keys.F5) 
                && (dtgDonDatHang.SelectedRows.Count > 0)
                && cbbVatTu.Enabled )
            {
                cbbVatTu.Focus();
            }
        }

        private void cbbVatTu_SelectedIndexChanged(object sender, EventArgs e)
        {
            if ((isFormLoad) && (isCbbNCCLoaded)&&(cbbVatTu.SelectedIndex!= -1))
            {
                txtNgang.Text = tbVatTu.Rows[cbbVatTu.SelectedIndex]["Ngang"].ToString();
                txtCao.Text = tbVatTu.Rows[cbbVatTu.SelectedIndex]["Cao"].ToString();
                txtSau.Text = tbVatTu.Rows[cbbVatTu.SelectedIndex]["Sau"].ToString();
            }
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            DexuatVatTu frmDXVT = new DexuatVatTu(conn, sNhanVienID, sTenNhanVien);
            frmDXVT.setEnableBtnLoad();
            frmDXVT.ShowInTaskbar = false;
            frmDXVT.ShowDialog();

            if (frmDXVT.isAcceptLoad)
            {
                DataTable tempTB = new DataTable();
                string cmd = "Load_DXVT_To_PMH N'" + frmDXVT.stDXVT.sHMSPID + "', N'" + frmDXVT.stDXVT.sVersion + "'";
                cmDO.getTable(conn, ref tempTB, cmd);

                // neu khong do data --> load len bi fail
                if (tempTB.Rows.Count == 0 )
                {
                    ShowMsg("Load data không thành công", 2);
                    return;
                }

                string sVTIDtemp = "";
                DataTable temp = new DataTable();
                cmd = "";
                string ret;

                string dtNgayDH = "";
                if (dtgDonDatHang.RowCount == 0)
                {
                    dtNgayDH = string.Format("{0:yyyy-MM-dd}", dtpNgayDatHang.Value);
                }
                else
                {
                    dtNgayDH = tbDataGrid.Rows[0]["NgayDatHang"].ToString();
                    dtNgayDH = string.Format("{0:d}", DateTime.Parse(dtNgayDH));
                }
                for (int i = 0; i < tempTB.Rows.Count; i++)
                {
                    sVTIDtemp = tempTB.Rows[i]["VTID"].ToString();
                    cmd = "select PMHID from DonDatHang where PMHID = N'"
                                    + currentPMHID + "' and VTID = N'" + sVTIDtemp + "'";

                    ret = cmDO.getTable(conn, ref temp, cmd);

                    if (ret != CommonHeader.NO_ERROR)
                    {
                        ShowMsg("kiểm tra dữ liệu trùng thất bại", 2);
                        return;
                    }

                    if (temp.Rows.Count > 0)
                    {
                        if (MessageBox.Show("Đã có data " + sVTIDtemp + " trong database, Bạn có muốn update?",
                                            "Confirm",
                                            MessageBoxButtons.YesNo,
                                            MessageBoxIcon.Warning) == DialogResult.Yes)
                        {

                            // Load data don dat hang dua vao DDHID
                            cmd = "DonDatHang_update N'" + currentPMHID + "'"
                                        + ",N'" + sVTIDtemp + "'"
                                        + ",N'" + tempTB.Rows[i]["Ngang"].ToString() + "'"
                                        + ",N'" + tempTB.Rows[i]["Cao"].ToString() + "'"
                                        + ",N'" + tempTB.Rows[i]["Sau"].ToString() + "'"
                                        + ",N'" + tempTB.Rows[i]["SoLuong"].ToString() + "'"
                                        + ",N' '"
                                        + ",N'" + dtNgayDH + "'"
                                        + ",N'" + sVTIDtemp + "'";

                            ret = cmDO.InsertUpdateRecord(conn, cmd);

                            if (ret != CommonHeader.NO_ERROR)
                            {
                                ShowMsg("Update dữ liệu bị gián đoạn, một số data không được update không thành công", 2);
                                break;
                            }
                        }
                    }
                    else
                    {
                        if (! InsertData(sVTIDtemp,
                            tempTB.Rows[i]["Ngang"].ToString(),
                            tempTB.Rows[i]["Cao"].ToString(),
                            tempTB.Rows[i]["Sau"].ToString(),
                            tempTB.Rows[i]["SoLuong"].ToString(),
                            " "))
                        {
                            ShowMsg("Insert bị gián đoạn, một số data không insert thành công", 2);
                            break;
                        }
                    }

                    if (cbbNCC.SelectedValue.ToString() == NCC_ALL_VALUE.ToString())
                    {
                        loadDataGrid(currentPMHID);
                    }
                    else
                    {
                        cbbNCC.SelectedValue = NCC_ALL_VALUE;
                    }
                    selectID("");
                    oldVTID = "";
                }
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (dtgDonDatHang.SelectedRows.Count == 0)
                return;

            int iCurrRow = dtgDonDatHang.CurrentCell.RowIndex;
            
            // Load data don dat hang dua vao DDHID
            string cmd = "Delete DonDatHang where PMHID = N'" + currentPMHID + "'"                        
                        + " AND VTID = N'" + oldVTID + "'";

            string ret = cmDO.InsertUpdateRecord(conn, cmd);

            if (ret != CommonHeader.NO_ERROR)
            {
                ShowMsg("Xóa dữ liệu không thành công", 2);
                return;
            }
            loadDataGrid(currentPMHID);
            if (dtgDonDatHang.Rows.Count > 0)
            {
                if (iCurrRow > dtgDonDatHang.RowCount - 1)
                {
                    iCurrRow = dtgDonDatHang.RowCount - 1;
                }                
                string sNextID = dtgDonDatHang.Rows[iCurrRow].Cells[0].Value.ToString();
                selectID(sNextID);
                oldVTID = sNextID;
                btnDelete.Enabled = true;
                btnUpdate.Enabled = true;
            }
            else
            {
                oldVTID = "";
                btnDelete.Enabled = false;
                btnUpdate.Enabled = false;
            }
        }

        private void xuấtReportToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (cbbNCC.SelectedValue.ToString() == NCC_ALL_VALUE.ToString())
                {
                    ShowMsg("Không thể đặt hàng nhiều nhà cung cấp trong 1 phiếu", 2);
                    return;
                }

                if (tbDataGrid.Rows.Count == 0)
                {
                    ShowMsg("Không có data để xuất report", 0);
                    return;
                }

                FormReport frmReprt = new FormReport("PhieuMuaHang"); ;
                
                frmReprt.tbSource = tbDataGrid;

                DataTable temp = new DataTable();
                string cmd = "select * from NhaCungCap where NCCID =N'"+cbbNCC.SelectedValue.ToString()+"'";

                string ret = cmDO.getTable(conn, ref temp, cmd);

                if (ret != CommonHeader.NO_ERROR)
                {
                    ShowMsg("Xuất report thất bại", 2);
                    return;
                }

                frmReprt.sTenNCC = temp.Rows[0]["TenCongTy"].ToString();
                frmReprt.sDiaChi = temp.Rows[0]["DiaChi"].ToString();
                frmReprt.sTel = temp.Rows[0]["Tel"].ToString();
                frmReprt.sFax = temp.Rows[0]["fax"].ToString();
                frmReprt.sEmail = temp.Rows[0]["Email"].ToString();                

                frmReprt.ShowInTaskbar = false;
                frmReprt.ShowDialog();
            }
            catch (System.Exception ex)
            {
                ShowMsg("Xuất report thất bại", 2);
            }
        }

    }
}
